package org.binglan.youziyuepai.controller;

import io.swagger.annotations.*;
import org.apache.commons.lang3.StringUtils;
import org.binglan.youziyuepai.controller.base.BasicController;
import org.binglan.youziyuepai.entity.*;
import org.binglan.youziyuepai.enums.code.ContactTypeEnum;
import org.binglan.youziyuepai.form.UpdateUserForm;
import org.binglan.youziyuepai.service.*;
import org.binglan.youziyuepai.utils.EnumUtils;
import org.binglan.youziyuepai.utils.ResponseVoUtils;
import org.binglan.youziyuepai.vo.ResponseVo;
import org.binglan.youziyuepai.vo.UserVo;
import org.binglan.youziyuepai.vo.UsetContactWayVo;
import org.n3r.idworker.Sid;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;


/**
 * @description:
 * @author: sanjin
 * @date: 2019/4/9 13:12
 */
@Api(tags = "用户相关业务接口")
@RestController
@RequestMapping("/user")
public class UserController extends BasicController {

    @Autowired
    UserService userService;

    @Autowired
    SchoolService schoolService;

    @Autowired
    PhotographyTagService photographyTagService;

    @Autowired
    UserToPhotographyTagService userToPhotographyTagService;

    @Autowired
    UserContactWayService userContactWayService;

    @Autowired
    UserFansService userFansService;

    @Autowired
    ImageService imageService;

    @ApiOperation(value = "获取用户信息", notes = "获取用户信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "认证token", required = true, paramType = "header", dataType = "string")
    })
    @GetMapping("")
    public ResponseVo getUserInfo() {
        // 判断用户是否登陆
        String userId = this.getUserIdByAuth();

        UserVo userVo = userService.queryUserVoByUserId(userId);

        return ResponseVoUtils.success(userVo);
    }

    @ApiOperation(value = "通过用户id获取用户信息", notes = "获取用户信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户id", required = true, paramType = "query", dataType = "string")
    })
    @GetMapping("/getUserInfo")
    public ResponseVo getUserInfoByUserId(@RequestParam String userId) {

        UserVo userVo = userService.queryUserVoByUserId(userId);

        return ResponseVoUtils.success(userVo);
    }


    @ApiOperation(value = "修改用户信息", notes = "修改用户信息，修改调用获取用户信息接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "认证token", required = true, paramType = "header", dataType = "string")
    })
    @PutMapping("")
    public ResponseVo updateUserInfo(@RequestBody UpdateUserForm userForm) {
        String userId = this.getUserIdByAuth();
        // 验证参数
        Integer schoolId = userForm.getSchoolId();
        if (schoolId != null && schoolService.getById(schoolId) == null) {
            return ResponseVoUtils.error("学校id错误");
        }
        List<Integer> userFormTagIds = userForm.getTagIds();
        if (userFormTagIds != null && !photographyTagService.isExistsIds(userFormTagIds)) {
            // 判断数据是否存在这些id
            return ResponseVoUtils.error("标签id错误");
        }
        Integer gender = userForm.getGender();
        if (gender != null && gender != 0 && gender != 1) {
            return ResponseVoUtils.error("性别错误");
        }
        String imageId = userForm.getImageId();
        Image image = null;
        if (StringUtils.isNotBlank(imageId)) {
            image = imageService.queryImageById(imageId);
            if (image == null)
                return ResponseVoUtils.error("图片不存在");
        }

        // 修改用户信息
        User user = new User();
        user.setId(userId);
        BeanUtils.copyProperties(userForm, user);

        if (image != null) {
            user.setImageId(image.getId());
        }
        boolean updateById = userService.updateById(user);
        if (!updateById) return ResponseVoUtils.error("修改失败");

        // 修改用户标签
        List<Integer> tagIds = userForm.getTagIds();
        List<UserToPhotographyTag> userToPhotographyTagList = new LinkedList<>();
        if (tagIds != null && tagIds.size() > 0) {
            // 删除用户原有标签
            userToPhotographyTagService.deleteAllByUserId(userId);
            // 标签id转对象
            tagIds.forEach(id -> {
                UserToPhotographyTag obj = new UserToPhotographyTag();
                obj.setUserId(userId);
                obj.setPhotographyTagId(id);
                userToPhotographyTagList.add(obj);
            });
            userToPhotographyTagService.saveUserToPhotographyTagByBatch(userToPhotographyTagList);
        }

        return ResponseVoUtils.success();
    }


    @ApiOperation(value = "修改用户联系方式", notes = "修改用户联系方式，修改调用获取用户信息接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "认证token", required = true, paramType = "header", dataType = "string"),
            @ApiImplicitParam(name = "contactType", value = "联系类型，1 qq,2 weixin,3 weibo", required = true, paramType = "query", dataType = "string"),
            @ApiImplicitParam(name = "contactMark", value = "联系号码", required = true, paramType = "query", dataType = "string")
    })
    @PostMapping("/contact")
    public ResponseVo updateUserContact(@RequestParam("contactType") Integer contactType,
                                        @RequestParam("contactMark") String contactMark) {
        String userId = this.getUserIdByAuth();
        if (StringUtils.isBlank(contactMark) || contactType == null) {
            return ResponseVoUtils.error("参数不能未空");
        }
        // 判断 contactType 是否在枚举类中包含
        ContactTypeEnum[] contactTypeEnums = ContactTypeEnum.values();
        for (int i = 0; i < contactTypeEnums.length; i++) {
            if (!contactTypeEnums[i].getCode().equals(contactType) && i == contactTypeEnums.length - 1)
                return ResponseVoUtils.error("联系类型错误");
            if (contactTypeEnums[i].getCode().equals(contactType))
                break;
        }

        userContactWayService.saveOrUpdateUserContactWay(userId, contactType, contactMark);

        return ResponseVoUtils.success();
    }


    @ApiOperation(value = "获取用户联系方式", notes = "获取用户所有的联系方式")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "认证token", required = true, paramType = "header", dataType = "string"),
    })
    @GetMapping("/contact")
    public ResponseVo getUserCntact() {
        String userId = this.getUserIdByAuth();
        List<UserContactWay> userContactWays = userContactWayService.queryAllUserContactWayByUserId(userId);
        if (userContactWays == null)
            return ResponseVoUtils.success();


        List<UsetContactWayVo> usetContactWayVos = userContactWays.stream().map(item -> {
            UsetContactWayVo obj = new UsetContactWayVo();
            BeanUtils.copyProperties(item, obj);
            obj.setContactName(EnumUtils.getMessageByCode(item.getContactType(), ContactTypeEnum.class));
            return obj;
        }).collect(Collectors.toList());
        return ResponseVoUtils.success(usetContactWayVos);
    }

    @ApiOperation(value = "用户关注接口", notes = "用户关注接口，修改调用获取用户信息接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "认证token", required = true, paramType = "header", dataType = "string"),
            @ApiImplicitParam(name = "attentionId", value = "关注id", required = true, paramType = "query", dataType = "string"),
    })
    @PostMapping("/attention")
    public ResponseVo attention(@RequestParam("attentionId") String attentionId) {
        String userId = this.getUserIdByAuth();
        if (StringUtils.isBlank(attentionId)) {
            return ResponseVoUtils.error("attentionId 不能为空");
        }
        // attentionId 不能是自己
        if (attentionId.equals(userId)) {
            return ResponseVoUtils.error("不能关注自己");
        }
        // attentionId 不存在
        User queryUserById = userService.queryUserById(attentionId);
        if (queryUserById == null) {
            return ResponseVoUtils.error("关注用户不存在");
        }

        UserFans userFans = new UserFans();
        userFans.setId(Sid.nextShort());
        userFans.setFansId(userId);
        userFans.setUserId(attentionId);

        return ResponseVoUtils.success();
    }


    @ApiOperation(value = "获取用户粉丝", notes = "获取用户粉丝")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "认证token", required = true, paramType = "header", dataType = "string"),
    })
    @PostMapping("/fans")
    public ResponseVo getUserFans() {
        String userId = this.getUserIdByAuth();
        List<UserVo> userVos = userFansService.queryFansUserVoByUserId(userId);

        return ResponseVoUtils.success(userVos);
    }

    @ApiOperation(value = "获取用户的关注用户", notes = "获取用户的关注用户")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "认证token", required = true, paramType = "header", dataType = "string"),
    })
    @PostMapping("/attentionUsers")
    public ResponseVo getUserAttentionUsers() {
        String userId = this.getUserIdByAuth();
        List<UserVo> userVos = userFansService.queryAttentionUserVoByUserId(userId);

        return ResponseVoUtils.success(userVos);
    }

}
